package com.ruoyi.common.utils;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Encoder;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author GyunChang
 */
public class TemplateDownUtils {

    private static final Logger logger = LoggerFactory.getLogger(TemplateDownUtils.class);

    public static XSSFWorkbook getXSSFWorkbook(Object object,String excelName) {
        XSSFWorkbook workbook =  null;
        ClassLoader classLoader = object.getClass().getClassLoader();
        InputStream input = classLoader.getResourceAsStream(excelName);
        logger.info("====input={}",input);
        try {
            workbook = new XSSFWorkbook(input);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(input!=null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return workbook;
    }


    /**
     * linux下创建temp文件
     */
    public static String createTempFile(String fileName) {
        //到jar包名
        String dirPath = System.getProperty("java.class.path");
        int firstIndex = dirPath.lastIndexOf(System.getProperty("path.separator")) + 1;
        int lastIndex = dirPath.lastIndexOf(File.separator) + 1;
        dirPath = dirPath.substring(firstIndex, lastIndex) + File.separator + "tempFileDir2";
        String filePath = dirPath + File.separator + fileName;
        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
            logger.info("文件下载目录:[{}]不存在，进行创建", dirPath);
            File dirFile = new File(dirPath);
            if (dirFile.exists()) {
                logger.info("文件下载目录[{}]创建SUCCESS", dirPath);
            } else {
                logger.info("文件下载目录[{}]创建FAILED", dirPath);
            }
        } else {
            logger.info("文件下载目录存在，地址为:[{}]", dirPath);
        }
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                logger.error("创建临时文件失败，error is :", e);
            }
        }
        return filePath;
    }



    public static String fileToBase64(String path) throws Exception {
        File file = new File(path);
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int)file.length()];
        inputFile.read(buffer);
        inputFile.close();
        String base = new BASE64Encoder().encode(buffer);
        file.delete();
        return base;
    }
}
